/*
 * @Author: MiNine
 * @Date: 2020-09-23 11:00:34
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-24 10:53:15
 * @Description: 
 */


const {
  TOKEN_KEY
} = require('./const');
const jwt = require('jsonwebtoken');

/**
 * @name: 判断token中的权限值是否满足要求
 * @param {type} req ,传入req请求
 * @param {type} Array ,传入一个权限组 如 ['1','2']
 * @return {type} Boolean 
 */
function permissionVerify(req, permissionArr = []) {

  const auth = req.get('Authorization');

  console.log(auth);

  const token = auth.split(' ')[1];
  console.log(token);
  const {
    permission
  } = jwt.verify(token, TOKEN_KEY);

  console.log("permission=" + permission);

  return permissionArr.some(item => item == permission);

}

function permissionVerifyItem(req, res, next, permissionArr) {

  const result = permissionVerify(req, permissionArr);
  if (result) {
    //权限验证通过
    console.log("permissionVerify successful");
    next();
  } else {
    console.log("NO permission , permissionVerify fail");
    res.send({
      status: 0,
      msg: "无权限进行此操作!"
    })
  }
}

function permission1(req, res, next) {
  const permissionArr = ['1'];
  permissionVerifyItem(req, res, next, permissionArr);
}

function permission5(req, res, next) {
  const permissionArr = ['5'];
  permissionVerifyItem(req, res, next, permissionArr);
}

function permission9(req, res, next) {
  const permissionArr = ['9'];
  permissionVerifyItem(req, res, next, permissionArr);
}

function permission19(req, res, next) {
  const permissionArr = ['1', '9'];
  permissionVerifyItem(req, res, next, permissionArr);
}

function permission159(req, res, next) {
  const permissionArr = ['1', '5', '9'];
  permissionVerifyItem(req, res, next, permissionArr);
}

module.exports = {
  permission1,
  permission5,
  permission9,
  permission19,
  permission159
}